//
//  GlobalDeviceInfo.m
//  YuanXinKit
//
//  Created by 晏德智 on 2016/10/27.
//  Copyright © 2016年 晏德智. All rights reserved.
//

#import "GlobalDeviceInfo.h"
#import <Foundation/Foundation.h>
#import <UIKit/UIKit.h>
#import <sys/utsname.h>
#import "DeviceUID.h"
#import "GlobalDeviceDataLibrary.h"
#import <WebKit/WebKit.h>

@implementation GlobalDeviceInfo

@synthesize machineName =_machineName;
/*
@synthesize systemName = _systemName;
@synthesize systemVersion = _systemVersion;
@synthesize deviceName =_deviceName;
 */
@synthesize bundleId = _bundleId;
@synthesize appVersion = _appVersion;
@synthesize buildNumber = _buildNumber;
@synthesize uniqueId =_uniqueId;

@synthesize deviceLocale =_deviceLocale;
@synthesize timezone =_timezone;
@synthesize userAgent =_userAgent;
@synthesize deviceCountry =_deviceCountry;
@synthesize model = _model;


+(instancetype)shareInstance {
    static dispatch_once_t onceToken;
    static GlobalDeviceInfo *manager = nil;
    dispatch_once(&onceToken, ^{
        manager = [[self alloc] init];
    });
    return manager;
}

- (instancetype)init{
    self = [super init];
    if(self){
        /*
        _bundleId =  [[NSBundle mainBundle] objectForInfoDictionaryKey:@"CFBundleIdentifier"];
        _appVersion = [[NSBundle mainBundle] objectForInfoDictionaryKey:@"CFBundleShortVersionString"];
        _buildNumber =  [[NSBundle mainBundle] objectForInfoDictionaryKey:@"CFBundleVersion"];
         */
    }
    return self;
}

- (NSString *)bundleId{
    if(!_bundleId){
        _bundleId = [NSBundle mainBundle].bundleIdentifier;
    }
    return _bundleId;
}

- (NSString *)appVersion{
    if(!_appVersion){
        _appVersion = [[NSBundle mainBundle] objectForInfoDictionaryKey:@"CFBundleShortVersionString"];
    }
    return _appVersion;
}

- (NSString *)buildNumber{
    if(!_buildNumber){
        _buildNumber =  [[NSBundle mainBundle] objectForInfoDictionaryKey:@"CFBundleVersion"];
    }
    return _buildNumber;
}


- (NSString *)systemName{
   return [UIDevice currentDevice].systemName;
}

- (NSString *)systemVersion{
   return [UIDevice currentDevice].systemVersion;
}

- (NSString *)deviceName{
    return [UIDevice currentDevice].name;
}

- (NSString *)uniqueId{
    if(!_uniqueId){
        _uniqueId = [DeviceUID uid];
    }
    return _uniqueId;
}

- (NSString*)machineName
{
    if(!_machineName){
        struct utsname systemInfo;
        
        uname(&systemInfo);
        
        _machineName = [NSString stringWithCString:systemInfo.machine
                                       encoding:NSUTF8StringEncoding];
    }
    return _machineName;
}

// 已废弃，请s使用 GlobalDeviceDataLibrary getDiviceName 方法
- (NSDictionary*)deviceNamesByCode {
    static NSDictionary* deviceNamesByCode = nil;
    
    if (!deviceNamesByCode) {
        
        deviceNamesByCode = @{@"i386"      :@"Simulator",
                              @"x86_64"    :@"Simulator",
                              @"iPod1,1"   :@"iPod Touch",      // (Original)
                              @"iPod2,1"   :@"iPod Touch",      // (Second Generation)
                              @"iPod3,1"   :@"iPod Touch",      // (Third Generation)
                              @"iPod4,1"   :@"iPod Touch",      // (Fourth Generation)
                              @"iPod5,1"   :@"iPod Touch",      // (Fifth Generation)
                              @"iPod7,1"   :@"iPod Touch",      // (Sixth Generation)
                              @"iPhone1,1" :@"iPhone",          // (Original)
                              @"iPhone1,2" :@"iPhone 3G",       // (3G)
                              @"iPhone2,1" :@"iPhone 3GS",      // (3GS)
                              @"iPad1,1"   :@"iPad",            // (Original)
                              @"iPad2,1"   :@"iPad 2",          //
                              @"iPad2,2"   :@"iPad 2",          //
                              @"iPad2,3"   :@"iPad 2",          //
                              @"iPad2,4"   :@"iPad 2",          //
                              @"iPad3,1"   :@"iPad",            // (3rd Generation)
                              @"iPad3,2"   :@"iPad",            // (3rd Generation)
                              @"iPad3,3"   :@"iPad",            // (3rd Generation)
                              @"iPhone3,1" :@"iPhone 4",        // (GSM)
                              @"iPhone3,2" :@"iPhone 4",        // iPhone 4
                              @"iPhone3,3" :@"iPhone 4",        // (CDMA/Verizon/Sprint)
                              @"iPhone4,1" :@"iPhone 4S",       //
                              @"iPhone5,1" :@"iPhone 5",        // (model A1428, AT&T/Canada)
                              @"iPhone5,2" :@"iPhone 5",        // (model A1429, everything else)
                              @"iPad3,4"   :@"iPad",            // (4th Generation)
                              @"iPad3,5"   :@"iPad",            // (4th Generation)
                              @"iPad3,6"   :@"iPad",            // (4th Generation)
                              @"iPad2,5"   :@"iPad Mini",       // (Original)
                              @"iPad2,6"   :@"iPad Mini",       // (Original)
                              @"iPad2,7"   :@"iPad Mini",       // (Original)
                              @"iPhone5,3" :@"iPhone 5c",       // (model A1456, A1532 | GSM)
                              @"iPhone5,4" :@"iPhone 5c",       // (model A1507, A1516, A1526 (China), A1529 | Global)
                              @"iPhone6,1" :@"iPhone 5s",       // (model A1433, A1533 | GSM)
                              @"iPhone6,2" :@"iPhone 5s",       // (model A1457, A1518, A1528 (China), A1530 | Global)
                              @"iPhone7,1" :@"iPhone 6 Plus",   //
                              @"iPhone7,2" :@"iPhone 6",        //
                              @"iPhone8,1" :@"iPhone 6s",       //
                              @"iPhone8,2" :@"iPhone 6s Plus",  //
                              @"iPhone8,4" :@"iPhone SE",       //
                              @"iPhone9,1" :@"iPhone 7",        // (model A1660 | CDMA)
                              @"iPhone9,3" :@"iPhone 7",        // (model A1778 | Global)
                              @"iPhone9,2" :@"iPhone 7 Plus",   // (model A1661 | CDMA)
                              @"iPhone9,4" :@"iPhone 7 Plus",   // (model A1784 | Global)
                              @"iPad4,1"   :@"iPad Air",        // 5th Generation iPad (iPad Air) - Wifi
                              @"iPad4,2"   :@"iPad Air",        // 5th Generation iPad (iPad Air) - Cellular
                              @"iPad4,3"   :@"iPad Air",        // 5th Generation iPad (iPad Air)
                              @"iPad4,4"   :@"iPad Mini 2",     // (2nd Generation iPad Mini - Wifi)
                              @"iPad4,5"   :@"iPad Mini 2",     // (2nd Generation iPad Mini - Cellular)
                              @"iPad4,6"   :@"iPad Mini 2",     // (2nd Generation iPad Mini)
                              @"iPad4,7"   :@"iPad Mini 3",     // (3rd Generation iPad Mini)
                              @"iPad4,8"   :@"iPad Mini 3",     // (3rd Generation iPad Mini)
                              @"iPad4,9"   :@"iPad Mini 3",     // (3rd Generation iPad Mini)
                              @"iPad5,1"   :@"iPad Mini 4",     // (4th Generation iPad Mini)
                              @"iPad5,2"   :@"iPad Mini 4",     // (4th Generation iPad Mini)
                              @"iPad5,3"   :@"iPad Air 2",      // 6th Generation iPad (iPad Air 2)
                              @"iPad5,4"   :@"iPad Air 2",      // 6th Generation iPad (iPad Air 2)
                              @"iPad6,3"   :@"iPad Pro 9.7-inch",// iPad Pro 9.7-inch
                              @"iPad6,4"   :@"iPad Pro 9.7-inch",// iPad Pro 9.7-inch
                              @"iPad6,7"   :@"iPad Pro 12.9-inch",// iPad Pro 12.9-inch
                              @"iPad6,8"   :@"iPad Pro 12.9-inch",// iPad Pro 12.9-inch
                              @"AppleTV2,1":@"Apple TV",        // Apple TV (2nd Generation)
                              @"AppleTV3,1":@"Apple TV",        // Apple TV (3rd Generation)
                              @"AppleTV3,2":@"Apple TV",        // Apple TV (3rd Generation - Rev A)
                              @"AppleTV5,3":@"Apple TV",        // Apple TV (4th Generation)
                              };
    }
    
    return deviceNamesByCode;
}

- (NSString*)model
{
    if(!_model){
        //NSString* deviceModelName = [[self deviceNamesByCode] objectForKey:self.machineName];
        NSString* deviceModelName = [[[GlobalDeviceDataLibrary sharedLibrery] getDiviceName] copy];
        
        if (!deviceModelName || [deviceModelName isEqualToString:@"Unknown"]) {
            // Not found on database. At least guess main device type from string contents:
            
            /* 直接去返回 机型代号（machineName）
            if ([self.machineName rangeOfString:@"iPod"].location != NSNotFound) {
                _model = @"iPod Touch";
            }
            else if([self.machineName rangeOfString:@"iPad"].location != NSNotFound) {
                _model = @"iPad";
            }
            else if([self.machineName rangeOfString:@"iPhone"].location != NSNotFound){
                _model = @"iPhone";
            }
            */
            // 机型名称未知的话，直接返回机型代号
            _model = self.machineName ?: @"Unknown";
        }else{
            _model = deviceModelName;
        }
    }
    
    return _model;
}

- (NSString*) userAgent
{
    if(!_userAgent){
//        UIWebView* webView = [[UIWebView alloc] initWithFrame:CGRectZero];
//        _userAgent = [webView stringByEvaluatingJavaScriptFromString:@"navigator.userAgent"];
//        webView = NULL;
        NSString *userAgent = nil;
    #if TARGET_OS_IOS
        // User-Agent Header; see http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.43
        userAgent = [NSString stringWithFormat:@"%@/%@ (%@; iOS %@; Scale/%0.2f)", [[NSBundle mainBundle] infoDictionary][(__bridge NSString *)kCFBundleExecutableKey] ?: [[NSBundle mainBundle] infoDictionary][(__bridge NSString *)kCFBundleIdentifierKey], [[NSBundle mainBundle] infoDictionary][@"CFBundleShortVersionString"] ?: [[NSBundle mainBundle] infoDictionary][(__bridge NSString *)kCFBundleVersionKey], [[UIDevice currentDevice] model], [[UIDevice currentDevice] systemVersion], [[UIScreen mainScreen] scale]];
    #elif TARGET_OS_WATCH
        // User-Agent Header; see http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.43
        userAgent = [NSString stringWithFormat:@"%@/%@ (%@; watchOS %@; Scale/%0.2f)", [[NSBundle mainBundle] infoDictionary][(__bridge NSString *)kCFBundleExecutableKey] ?: [[NSBundle mainBundle] infoDictionary][(__bridge NSString *)kCFBundleIdentifierKey], [[NSBundle mainBundle] infoDictionary][@"CFBundleShortVersionString"] ?: [[NSBundle mainBundle] infoDictionary][(__bridge NSString *)kCFBundleVersionKey], [[WKInterfaceDevice currentDevice] model], [[WKInterfaceDevice currentDevice] systemVersion], [[WKInterfaceDevice currentDevice] screenScale]];
    #elif defined(__MAC_OS_X_VERSION_MIN_REQUIRED)
        userAgent = [NSString stringWithFormat:@"%@/%@ (Mac OS X %@)", [[NSBundle mainBundle] infoDictionary][(__bridge NSString *)kCFBundleExecutableKey] ?: [[NSBundle mainBundle] infoDictionary][(__bridge NSString *)kCFBundleIdentifierKey], [[NSBundle mainBundle] infoDictionary][@"CFBundleShortVersionString"] ?: [[NSBundle mainBundle] infoDictionary][(__bridge NSString *)kCFBundleVersionKey], [[NSProcessInfo processInfo] operatingSystemVersionString]];
    #endif
        if (userAgent) {
            if (![userAgent canBeConvertedToEncoding:NSASCIIStringEncoding]) {
                NSMutableString *mutableUserAgent = [userAgent mutableCopy];
                if (CFStringTransform((__bridge CFMutableStringRef)(mutableUserAgent), NULL, (__bridge CFStringRef)@"Any-Latin; Latin-ASCII; [:^ASCII:] Remove", false)) {
                    userAgent = mutableUserAgent;
                }
            }
            _userAgent = userAgent;
        } else {
            _userAgent = @"";
            [WKWebView.new evaluateJavaScript:@"navigator.userAgent" completionHandler:^(id _Nullable result, NSError * _Nullable error) {
                _userAgent = result ?: @"";
            }];
        }
    }
    
    return _userAgent;
}

- (NSString*) deviceLocale
{
    if (!_deviceLocale){
        _deviceLocale = [[NSLocale preferredLanguages] objectAtIndex:0];
    }
    return _deviceLocale;
}

- (NSString*) deviceCountry
{
    if(!_deviceCountry){
        _deviceCountry = [[NSLocale currentLocale] objectForKey:NSLocaleCountryCode];
    }
    return _deviceCountry;
}

- (NSString*) timezone
{
    if(!_timezone){
        NSTimeZone *currentTimeZone = [NSTimeZone localTimeZone];
        _timezone = currentTimeZone.name;
    }
    return _timezone;
}

- (bool)isEmulator
{
    //return [self.model isEqual: @"Simulator"];
    return [self.model containsString: @"Simulator"];
}


@end
